package com.chinawayltd.ews.sample.service.basicInfo.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.mapper.TLimiterMapper;
import com.chinawayltd.ews.sample.mapper.TLogMapper;
import com.chinawayltd.ews.sample.mapper.basicInfo.LimiterExtendMapper;
import com.chinawayltd.ews.sample.model.TLimiter;
import com.chinawayltd.ews.sample.model.TLimiterExample;
import com.chinawayltd.ews.sample.model.TLimiterExample.Criteria;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.service.base.impl.BaseServiceImpl;
import com.chinawayltd.ews.sample.service.basicInfo.LimiterService;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExportCloumsModel;
import com.chinawayltd.ews.sample.web.query.LimiterGirdQuery;

/**
 * @program: greeProject
 * @description 实现类
 * @author: chenxin
 * @create: 2018年4月11日 下午10:50:03
 */
@Service
public class LimiterServiceImpl extends BaseServiceImpl implements LimiterService {
	private static final SimpleDateFormat HHMM = new SimpleDateFormat("HH:mm");
	private static final SimpleDateFormat YYYYMMDD_HHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final String tableName = "T_LIMITER";

    @Autowired
    private TLimiterMapper tLimiterMapper;
    @Autowired
    private LimiterExtendMapper limiterExtendMapper;
    @Autowired
	private TLogMapper tLogMapper;
    
    @Override
	public List<TLimiter> list(LimiterGirdQuery queryParam) {
		 return limiterExtendMapper.list(queryParam);
	}
    
	@Override
	public TLimiter getById(Long id) throws Exception{
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		return tLimiterMapper.selectByPrimaryKey(id);
	}

	@Override
	public int add(TLimiter tLimiter) throws Exception {
		if(HHMM.parse(tLimiter.getBigLimiterTime()).getTime() >= HHMM.parse(tLimiter.getEndLimiterTime()).getTime()){
			throw new BusinessException("开始时间要小于结束时间");
		}
		tLimiter.setCreateTime(new Date());
		tLimiter.setUpdateTime(new Date());
		if(tLimiter.getPeriodTime()==null)throw new BusinessException("限行时间不能为空！");
		int result = limiterExtendMapper.insert(tLimiter);
		if (result > 0) {
			TLog log = new TLog();
			log.setDataId(tLimiter.getId());
			log.setTableName(tableName);
			log.setOperationType(1);
			log.setOperationUser(getCurrentUser().getRealname());
			log.setCreateTime(new Date());
			tLogMapper.insertSelective(log);// 增加日记
		}
		return result;
	}

	@Override
	public int update(TLimiter tLimiter) throws Exception {
		if(tLimiter.getPeriodTime()==null)throw new BusinessException("限行时间不能为空！");
		if(HHMM.parse(tLimiter.getBigLimiterTime()).getTime() > HHMM.parse(tLimiter.getEndLimiterTime()).getTime()){
			throw new BusinessException("开始时间要小于结束时间");
		}
		tLimiter.setUpdateTime(new Date());
		int result = tLimiterMapper.updateByPrimaryKeySelective(tLimiter);
		if (result > 0) {
			TLog log = new TLog();
			log.setDataId(tLimiter.getId());
			log.setTableName(tableName);
			log.setOperationUser(getCurrentUser().getRealname());
			log.setOperationType(2);
			log.setCreateTime(new Date());
			tLogMapper.insertSelective(log);// 增加日记
		}
		return result;
		
	}

	@Override
	public int delete(Long id) throws Exception {
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		return tLimiterMapper.deleteByPrimaryKey(id);
	}

	@Override
	@Transactional
	public int deletesByIds(String[] ids) {
		return limiterExtendMapper.deleteAll(ids);
	}

	@Override
	@Transactional
	public ExcelObjModel insertList(List<PageData> list) throws Exception {
		ExcelObjModel model = new ExcelObjModel();
		List<Object> mapList = new ArrayList<>();
		model.setCode(0); // 0没添加1添加成功，否则有添加不成功的
		int result = 0;
		Date now = new Date();
		
		//遍历读取的Excel数据，判断数据的正确性
		for (PageData pd : list) {
			try {
				TLimiter tLimiter = new TLimiter();
				String limiterName = pd.getString("var0");
				tLimiter.setLimiterName(limiterName);
				String bigLimiterTime = pd.getString("var1");
				String endLimiterTime = pd.getString("var2");
				if(StringUtils.isNotBlank(bigLimiterTime)){
					bigLimiterTime = formatTimeToHHMM(bigLimiterTime);
					tLimiter.setBigLimiterTime(bigLimiterTime);
				}
				if(StringUtils.isNotBlank(endLimiterTime)){
					endLimiterTime = formatTimeToHHMM(endLimiterTime);
					tLimiter.setEndLimiterTime(endLimiterTime);
				}
				String periodTime = pd.getString("var3");
				if(StringUtils.isNotBlank(periodTime)){
					tLimiter.setPeriodTime((short)Integer.valueOf(periodTime).intValue());
				}
				
				
				//将对象转化为map，判断是否为空
				Map<String, Object> map = com.chinawayltd.ews.sample.util.MapUtils.objectToMap(tLimiter);
				if(StringUtils.isBlank(limiterName) || StringUtils.isBlank(bigLimiterTime) || StringUtils.isBlank(endLimiterTime)){
					map.put("describe", "填写的字段不能为空");
					mapList.add(map);
					continue;
				}
				
				if(endLimiterTime.equals("00:00") || endLimiterTime.equals("0:00")){
					map.put("describe", "结束时间不能为00:00");
					mapList.add(map);
					continue;
				}
				//判断开始是否小于结束时间
				if(HHMM.parse(bigLimiterTime).getTime() > HHMM.parse(endLimiterTime).getTime()){
					map.put("describe", "开始时间要小于结束时间");
					mapList.add(map);
					continue;
				}
				
				tLimiter.setCreateTime(now);
				tLimiter.setUpdateTime(now);
				
				Map<String, Object> loadData = this.toLoadData(tLimiter);
				if(MapUtils.getInteger(loadData, "result") > 0 ){
					map.put("describe", "导入成功");
					mapList.add(map);
				}else{
					String describe = MapUtils.getString(loadData, "describe");
					map.put("describe", StringUtils.isBlank(describe) ? "导入异常" : describe);
					mapList.add(map);
					continue;
				}
				model.setCode(result);
			} catch (Exception e) {
				e.printStackTrace();
				model.setCode(0);
				Map<String, Object> exceptionMap = new HashMap<>();
				exceptionMap.put("limiterName", pd.getString("var0"));
				exceptionMap.put("bigLimiterTime", pd.getString("var1"));
				exceptionMap.put("endLimiterTime", pd.getString("var2"));
				exceptionMap.put("periodTime", pd.getString("var3"));
				exceptionMap.put("describe", "数据异常，导入失败");
				mapList.add(exceptionMap);
			}
			
		}
		model.setList(mapList);
		List<ExportCloumsModel> cloums = new ArrayList<>();
		if(mapList.size() > 0){
			cloums.add(new ExportCloumsModel("限行条件名称", "limiterName"));
			cloums.add(new ExportCloumsModel("限行开始时间", "bigLimiterTime"));
			cloums.add(new ExportCloumsModel("限行结束时间", "endLimiterTime"));
			cloums.add(new ExportCloumsModel("总部限行路程时间", "periodTime"));
			cloums.add(new ExportCloumsModel("导入描述", "describe"));
		}
		model.setCloums(cloums);
		return model;
	}
	
	private String formatTimeToHHMM( String time) throws ParseException {
		SimpleDateFormat sdf = time.length() < 6 ? HHMM : YYYYMMDD_HHMMSS;
		time = HHMM.format(sdf.parse(time));
		return time;
	}

	/**导入数据，重复则更新
	 * @author Fay
	 * @date 2018年5月7日 下午3:02:57
	 * @param tLimiter
	 * @return
	 */
	@Transactional
	private Map<String, Object> toLoadData(TLimiter tLimiter) {
		int result = 0;
		TLog log = new TLog();
		Map<String, Object> map = new HashMap<>();
		
		TLimiterExample example = new TLimiterExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andLimiterNameEqualTo(tLimiter.getLimiterName());
//		createCriteria.andBigLimiterTimeEqualTo(tLimiter.getBigLimiterTime());
//		createCriteria.andEndLimiterTimeEqualTo(tLimiter.getEndLimiterTime());
		List<TLimiter> selectByExample = tLimiterMapper.selectByExample(example);
		
		if(selectByExample.size() > 0){
			result = 0;
			String describe = "限行条件名称重复";
			map.put("describe", describe);
		}else{
			result = limiterExtendMapper.insert(tLimiter);
		}
		if(result > 0){
    		log.setDataId(tLimiter.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setOperationType(1);
    		log.setCreateTime(new Date());
    		log.setUpdateTime(new Date());
    		tLogMapper.insert(log);
		}
		map.put("result", result);
		return map;
	}

	@Override
	public List<TLimiter> getLimiterByNameAndId(Long limiterId, String limiterName) {
		Map<String, Object> map = new HashMap<>();
		map.put("limiterId", limiterId);
		map.put("limiterName", limiterName);
		return limiterExtendMapper.getLimiterByNameAndId(map);
	}
 
}
